package cn.net.dpi.shp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.net.dpi.shp.mapper.BxfCcgMapper;
import cn.net.dpi.shp.model.entity.BxfCcg;
import cn.net.dpi.shp.model.entity.BxfJunction;
import cn.net.dpi.shp.model.entity.BxfLan;
import cn.net.dpi.shp.service.BxfCcgService;
import cn.net.dpi.shp.service.ShapefileService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.Point;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author DPI110
* @description 针对表【bxf_ccg】的数据库操作Service实现
* @createDate 2025-05-29 15:31:26
*/
@Service
@Slf4j
public class BxfCcgServiceImpl extends ServiceImpl<BxfCcgMapper, BxfCcg>
    implements BxfCcgService, ShapefileService {
    private static final String ENTITY_BASE_NAME = BxfCcg.class.getAnnotation(TableName.class).value();

    /**
     * 检查并清理当前shp文件，已经存在先删除
     *
     * @param fileId
     */
    @DS("#area")
    private void checkAndClearRecords(Long fileId, String area) {
        /**
     * 检查下是否已经存在，已经存在先删除
     */
        LambdaQueryWrapper<BxfCcg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BxfCcg::getFileId, fileId);
        if (this.exists(queryWrapper)) {
            if (this.remove(queryWrapper)) {
                log.warn("BxfCcg fileId:{} already exists, delete success and prerare parse again.", fileId);
            } else {
                log.warn("BxfCcg fileId:{} already exists, delete failed and do not parse, maybe check.", fileId);
            }
        }
    }

    private List<BxfCcg> parseShpfile(Long fileId, String filePath) {
        List<Map> mapList = defaultParseShpfile(filePath);
        if (mapList.isEmpty()) {
            return Collections.EMPTY_LIST;
        }
        List<BxfCcg> collect = mapList.stream().map(m -> {
            CopyOptions copyOptions = CopyOptions.create().setIgnoreProperties(SHP_DEFAULT_GEM_NAME)
                    .setIgnoreCase(true);
            BxfCcg obj = new BxfCcg();
            BeanUtil.copyProperties(m, obj, copyOptions);
            Geometry o = (Geometry) m.get(SHP_DEFAULT_GEM_NAME);
            if (o instanceof Point) {
                obj.setTheGeom((Point) o);
            } else if (o instanceof MultiPoint) {
                MultiPoint theGeom = (MultiPoint) o;
                Point geometry = (Point) theGeom.getGeometryN(0);
                obj.setTheGeom(geometry);
            } else {
                log.warn("NOT Point or MultiPoint");
            }
            obj.setFileId(fileId);
            return obj;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    @DS("#area")
    public boolean parseShpfile(Long fileId, String baseName, String filePath, String version, Integer versionFlag, String area) {
        if (StringUtils.equalsIgnoreCase(baseName, ENTITY_BASE_NAME)) {

            checkAndClearRecords(fileId, area);

            List<BxfCcg> collect = parseShpfile(fileId, filePath);

            if (!CollectionUtils.isEmpty(collect)) {
                if (this.saveBatch(collect)) {
                    log.warn("BxfCcg saveBatch success,size:{}", collect.size());
                    return true;
                } else {
                    log.warn("BxfCcg saveBatch failed,size:{}", collect.size());
                }
            } else {
                log.warn("BxfCcg file:{},has no result", filePath);
            }
        }
        return false;
    }
}




